package com.GroupSix.service;

import com.GroupSix.service.QuestionBankService;
import com.GroupSix.dao.WrongQuestionDao;
import com.GroupSix.entity.QuestionBankEntity;
import com.GroupSix.entity.WrongQuestionEntity;
import com.GroupSix.vo.WrongPracticVo;
import com.GroupSix.vo.WrongQuestionVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service("wrongQuestionService")
public class WrongQuestionServiceImpl extends ServiceImpl<WrongQuestionDao, WrongQuestionEntity> implements WrongQuestionService {
    @Autowired
    private QuestionBankService questionBankService; // 添加依赖注入

    public boolean addWrongQuestionManually(Integer userId, Long questionId, String comment) {
        // 检查是否已存在相同的记录
        LambdaQueryWrapper<WrongQuestionEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WrongQuestionEntity::getUserId, userId)
                .eq(WrongQuestionEntity::getQuestionId, questionId)
                .eq(WrongQuestionEntity::getIsActive, 1); // 仅检查激活的记录

        if (this.getOne(queryWrapper) != null) {
            // 如果已存在记录，直接返回 false 或抛出异常
            return false;
        }

        // 如果不存在，创建新的错题记录
        WrongQuestionEntity wrongQuestion = new WrongQuestionEntity();
        wrongQuestion.setUserId(userId);
        wrongQuestion.setQuestionId(questionId);
        wrongQuestion.setCountIncorrect(1); // 默认错误次数设置为 1
        wrongQuestion.setCountCorrect(0); // 初始正确次数为 0
        wrongQuestion.setComment(comment != null ? comment : "手动添加的错题"); // 添加备注
        wrongQuestion.setIsActive(1); // 激活状态

        return this.save(wrongQuestion);
    }


    public boolean deleteWrongQuestion(Integer userId, Long questionId) {
        // 构造查询条件
        LambdaQueryWrapper<WrongQuestionEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WrongQuestionEntity::getUserId, userId)
                .eq(WrongQuestionEntity::getQuestionId, questionId)
                .eq(WrongQuestionEntity::getIsActive, 1); // 仅删除激活的记录

        // 查询是否存在对应记录
        WrongQuestionEntity existingRecord = this.getOne(queryWrapper);
        if (existingRecord != null) {
            existingRecord.setIsActive(0); // 标记为逻辑删除
            return this.updateById(existingRecord); // 更新记录
        }
        return false; // 记录不存在，返回 false
    }

    public int autoDeleteWrongQuestions() {
        // 构造查询条件：错误次数 + 正确次数 ≥ 10 且 正确率 > 90%
        LambdaQueryWrapper<WrongQuestionEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(WrongQuestionEntity::getCountIncorrect, 1) // 错误次数至少为 1
                .apply("count-correct + count_incorrect >= 10") // 总次数 ≥ 10
                .apply("count_correct / (count_correct + count_incorrect) > 0.9") // 正确率 > 90%
                .eq(WrongQuestionEntity::getIsActive, 1); // 仅处理激活的错题

        // 查询符合条件的错题
        List<WrongQuestionEntity> toBeDeleted = this.list(queryWrapper);

        // 将符合条件的错题标记为逻辑删除
        for (WrongQuestionEntity wrongQuestion : toBeDeleted) {
            wrongQuestion.setIsActive(0); // 标记为逻辑删除
            this.updateById(wrongQuestion); // 更新记录
        }

        // 返回被删除的记录数
        return toBeDeleted.size();
    }

    public boolean updateComment(Integer userId, Long questionId, String comment) {
        LambdaQueryWrapper<WrongQuestionEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WrongQuestionEntity::getUserId, userId)
                .eq(WrongQuestionEntity::getQuestionId, questionId)
                .eq(WrongQuestionEntity::getIsActive, 1);

        WrongQuestionEntity existingRecord = this.getOne(queryWrapper);
        if (existingRecord != null) {
            existingRecord.setComment(comment);
            return this.updateById(existingRecord);
        }
        return false;
    }

    public List<WrongQuestionVo> getWrongQuestionsByUserId(Integer userId, Integer qscourse) {
        LambdaQueryWrapper<WrongQuestionEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WrongQuestionEntity::getUserId, userId)
                .eq(WrongQuestionEntity::getIsActive, 1);
        //获取错误题库
        List<WrongQuestionEntity> wrongQuestions = this.list(queryWrapper);
        return joinList(wrongQuestions, qscourse);
    }


    public List<WrongQuestionVo> getWrongQuestionsSortedByField(Integer userId, String orderBy, String orderDirection, Integer qscourse) {
        //获取单向列表wrongquestion
        QueryWrapper<WrongQuestionEntity> queryWrapperx = new QueryWrapper<WrongQuestionEntity>()
                .eq("user_id", userId)
                .eq("is_active", 1);
//        if (!StringUtils.isEmpty(orderDirection) && !StringUtils.isEmpty(orderBy)) {
//            if (orderDirection.equals("asc")) {
//                queryWrapperx.orderByAsc(orderBy.toLowerCase());
//            }else{
//                queryWrapperx.orderByDesc(orderBy.toLowerCase());
//            }
//        }
        List<WrongQuestionEntity> wrongQuestions = this.list(queryWrapperx);
        List<WrongQuestionVo>  reList=this.joinList(wrongQuestions, qscourse);
        if (!StringUtils.isEmpty(orderDirection) && !StringUtils.isEmpty(orderBy)) {
            if (orderDirection.equals("asc")) {
                //根据正确率正向排序
                if (orderBy.equals("accuracy")){
                    reList.sort(Comparator.comparingInt(vo->vo.getWrongQuestion().getCountCorrect()/(vo.getWrongQuestion().getCountCorrect()+vo.getWrongQuestion().getCountIncorrect())));
                }
                //根据错误次数正向排序
                if (orderBy.equals("score")){
                    reList.sort(Comparator.comparingInt(vo->vo.getQuestionBank().getQsscore()));
                }
                //根据难度正向排序
                if (orderBy.equals("difficulty")){
                    reList.sort(Comparator.comparingInt(vo->vo.getQuestionBank().getQsdifficulty()));
                }
            }else{
                //根据正确率倒序
                if (orderBy.equals("accuracy")){
                    reList.sort(Comparator.comparingInt((WrongQuestionVo vo)->vo.getWrongQuestion().getCountCorrect()/(vo.getWrongQuestion().getCountCorrect()+vo.getWrongQuestion().getCountIncorrect())).reversed());
                }
                //根据错误次数倒序
                if (orderBy.equals("score")){
                    reList.sort(Comparator.comparingInt((WrongQuestionVo vo)->vo.getQuestionBank().getQsscore()).reversed());
                }
                //根据难度倒序
                if (orderBy.equals("difficulty")){
                    reList.sort(Comparator.comparingInt((WrongQuestionVo vo)->vo.getQuestionBank().getQsdifficulty()).reversed());
                }
            }
        }
        return reList;
    }

    @Override
    public List<WrongPracticVo> randWrongByNum(Integer userId, Integer num, Integer qscourse) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_Id", userId);

        // 构造查询条件
        if (null != qscourse && !"".equals(qscourse)) {
            QueryWrapper questionWrapper = new QueryWrapper();
            questionWrapper.eq("qscourse", qscourse);
            List<QuestionBankEntity> questionBankEntities = questionBankService.list(questionWrapper);
            if (null != questionBankEntities && questionBankEntities.size() > 0) {
                List<Long> questionIds = questionBankEntities.stream().map(QuestionBankEntity::getId).collect(Collectors.toList());
                qw.in("question_id", questionIds);
            }
        }
        qw.orderBy(true, false, "rand()");
        qw.last("limit " + num);

        return this.joinListP(this.list(qw), qscourse);
    }


    public List<WrongQuestionVo> joinList(List<WrongQuestionEntity> wrongQuestions, Integer qscourse) {
        List<WrongQuestionVo> resultList = new ArrayList<>();
        for (WrongQuestionEntity wrongQuestion : wrongQuestions) {
            //获取题目
            QueryWrapper qsWrapper = new QueryWrapper();
            if (null != qscourse) {
                qsWrapper.eq("qscourse", qscourse);
            }
            qsWrapper.eq("id", wrongQuestion.getQuestionId());
            QuestionBankEntity question = questionBankService.getOne(qsWrapper);
            if (null != question) {
                WrongQuestionVo item = new WrongQuestionVo();

                item.setWrongQuestion(wrongQuestion);
                item.setQuestionBank(question);
                resultList.add(item);
            }
        }
        return resultList;
    }

    //练习题获取
    public List<WrongPracticVo> joinListP(List<WrongQuestionEntity> wrongQuestions, Integer qscourse) {
        List<WrongPracticVo> resultList = new ArrayList<>();
        for (WrongQuestionEntity wrongQuestion : wrongQuestions) {
            //获取题目
            QueryWrapper qsWrapper = new QueryWrapper();
            if (null != qscourse) {
                qsWrapper.eq("qscourse", qscourse);
            }
            qsWrapper.eq("id", wrongQuestion.getQuestionId());
            QuestionBankEntity question = questionBankService.getOne(qsWrapper);
            if (null != question) {
                WrongPracticVo item = new WrongPracticVo();
                item.setWrongQuestion(wrongQuestion);
                item.setQscontent(question.getQscontent());
                List<Map<String,String>> answerList = new ArrayList<>();
                if (question.getQsA() != null) {
                    Map<String,String> mapA = new HashMap<>();
                    mapA.put("A",question.getQsA());
                    answerList.add(mapA);
                }
                if (question.getQsB() != null) {
                    Map<String,String> mapB = new HashMap<>();
                    mapB.put("B",question.getQsB());
                    answerList.add(mapB);
                }
                if (question.getQsC() != null) {
                    Map<String,String> mapC = new HashMap<>();
                    mapC.put("C",question.getQsC());
                    answerList.add(mapC);
                }
                if (question.getQsD() != null) {
                    Map<String,String> mapD = new HashMap<>();
                    mapD.put("D",question.getQsD());
                    answerList.add(mapD);
                }
                if (question.getQsE() != null) {
                    Map<String,String> mapE = new HashMap<>();
                    mapE.put("E",question.getQsE());
                    answerList.add(mapE);
                }
                item.setAnswerList(answerList);
                resultList.add(item);
            }
        }
        return resultList;
    }

}



